<template>
	<div class="message-container" ref="messageRef">
		<message-area
			title="留言板"
			:subTitle="`${data.total}`"
			:isListLoading="isDataLoading"
			:list="data.rows"
			@submit="handleSubmit"
		></message-area>
		<div class="more" :class="{ moreClass: hasMore }">{{ slideText }}</div>
	</div>
</template>

<script>
import MessageArea from '@/components/MessageArea'
import fetchData from '@/mixins/fetchData'
import mainScroll from '@/mixins/mianScroll.js'
import * as messageApi from '@/api/message.js'
export default {
	name: 'Message',
	mixins: [fetchData({ total: 0, rows: [] }), mainScroll('messageRef')],
	components: {
		MessageArea,
	},
	data() {
		return {
			page: 1,
			limit: 10,
		}
	},
	created() {
		this.$bus.$on('mainScroll', this.handleScrollEle)
	},
	methods: {
		async fetchData() {
			return await messageApi.getMessage(this.page, this.limit)
		},
		async handleSubmit(data, callback) {
			const res = await messageApi.postMessage(data)
			callback('感谢您的留言!')
			this.data.total++
			this.data.rows.unshift(res)
		},
		handleScrollEle(domEle) {
			if (this.isDataLoading || !domEle) return
			const scrollTop = domEle.scrollTop
			const bottomHeight = domEle.scrollHeight - domEle.clientHeight
			if (bottomHeight - scrollTop < 20) {
				this.fetchMore()
			}
		},
		async fetchMore() {
			if (!this.hasMore) return
			this.isDataLoading = true
			this.page++
			const res = await this.fetchData()
			this.data.total = res.total
			this.data.rows = this.data.rows.concat(res.rows)
			this.isDataLoading = false
		},
	},
	computed: {
		hasMore() {
			return this.data.rows.length < this.data.total
		},
		slideText() {
			return this.hasMore ? '----下滑加载更多----' : '----没有更多了----'
		},
	},
}
</script>

<style lang="less" scoped>
@import '~@/styles/basic/var.less';
.message-container {
	width: 100%;
	height: 100%;
	overflow-y: auto;
	padding: 25px 0;
	scroll-behavior: smooth;
}
.message-area-container {
	width: 700px;
	margin: 0 auto;
}
.more {
	text-align: center;
	color: @gray;
}
.moreClass {
	color: @primary;
}
</style>
